<?php

// 批量上传文件到oss
// +------------------------------------------------------
declare(strict_types=1);

namespace app\api\controller\v1;

use think\facade\Db;
use app\common\common\IndexController;
use app\common\services\OSS;
use app\common\services\Task;
use app\common\services\UserServices;
use app\common\model\User as UserModel;
use app\common\model\Member as MemberModel;
use app\common\model\SubOrder as SubOrderModel;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\Order as OrderModel;
use app\common\model\RefundOrder as RefundOrderModel;
use app\common\services\OrderServices;
use app\common\services\FinanceServices;
use app\common\model\UserUpLog as UserUpLogModel;
use app\common\model\UserAchievement as UserAchievementModel; // 业绩统计
use app\common\model\Withdrawal as WithDrawalModel;
use app\common\model\BackMoney as BackMoneyModel;
use app\common\controller\Huigongbao;
use app\common\services\SendMsg;

/**
 * @xk 批量上传oss
 */
class Ajax extends IndexController
{
    public function Cleanusers(UserModel $userModel, UserServices $userServices){
        
        
        // $time=date('Y-m-d',strtotime('+30 days', time()));
        $time=date('Y-m-d',strtotime('-30 days', time()));
        // $time=date('Y-m-d',strtotime('-1 days', time()));
        $where['level']=1;
        $where['back_money']=0;
        $where['all_back_money']=0;
        $where['frozen_money']=0;
        $where['all_achievement_price']=0;
        // var_dump($where);die;
        // $where['raw'] = '(level_1_count+level_2_count+level_3_count+level_4_count+level_5_count) = 0';
        // $wherese=['exp','level_1_count+level_2_count+level_3_count+level_4_count+level_5_count = 0'];

        // $where['(level_1_count+level_2_count+level_3_count+level_4_count+level_5_count)']=0;
        $user_list = $userModel->where($where)->where(function ($query) {  
        $query->whereRaw('level_1_count+level_2_count+level_3_count+level_4_count+level_5_count = 0');  
    })->whereTime('create_time', '<', $time)->field('`user_id`,`user_sn`,`user_name`,`level`,`l_user_sn`,`is_all_bind`,(level_1_count + level_2_count + level_3_count + level_4_count + level_5_count) as level_count')->limit(50)->select();
       
        // $user_count = $userModel->where($where)->whereTime('create_time', '<', $time)->field('`user_id`,`user_sn`,`user_name`,`level`,`l_user_sn`,`is_all_bind`')->count();
        // var_dump($user_list);die;
        foreach($user_list as $user_info){
            var_dump($user_info['user_sn']);
            $userServices->syncCheckUp($user_info['user_sn'], $user_info['l_user_sn'], $user_info['user_sn'], $user_info['l_user_sn'], $user_info['level'], 'chanageOut');
            $where_find['user_id']=$user_info['user_id'];
            // var_dump($where_find);
            $rr=DB::name('user')->where($where_find)->delete();
            // var_dump($rr);die;
            
        }
        echo "执行成功";
        
    }
    
    public function chanage_upload_size($dir_name)
    {
        $result = false;
        if (is_dir($dir_name)) {
            if ($handle = opendir($dir_name)) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != '.' && $item != '..') {
                        if (is_dir($dir_name . '/' . $item)) {
                            $this->chanage_upload_size($dir_name . '/' . $item);
                        } else {
                            $newarray = explode(".", $dir_name.'/'.$item);
                            $type = $newarray[count($newarray)-1];
                            $image = Image::open($dir_name . '/' . $item);
                            dump($image);
                        }
                    }
                }
                closedir($handle);
            }
        }
    }
    /**
     * @xk 执行用户数据导入
     * @method                                      createUser
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-14Tfalse14:false55:false33+080
     */
    public function updateUserCount(Huigongbao $huigongbao,OrderServices $orderServices,FinanceServices $financeServices,UserModel $userModel,RefundOrderModel $refundOrderModel)
    {
        // $param = request()->param();
        // $user_sn = isset($param['user_sn'])?$param['user_sn']:'';
        // $condition = [];
        // $user_array = ['10472072','10917421','27340482','74187742','03495647','91435594'];
        // if($user_array){
        //     foreach ($user_array as $value) {
        //         $condition  = [];
        //         $condition[] = ['user_sn','=',$value];
        //         $userModel->where($condition)->save(['is_check'=>0,'card_num'=>'']);
        //         var_dump($value.'数据清理成功\n');
        //     }
        // }
        // echo "数据全部清理成功";
        // die();
        // Db::startTrans();
        // try {
        //     $data = [];
        //     $data['refund_order_sn'] = '20240409123309810029';
        //     $data['user_sn'] = '84289021';
        //     $data['refund_check_price'] = '128.00';
        //     $data['pay_order_sn'] = '740620240408164278147857748489';
        //     $data['type'] = 2;
        //     $result = [];
        //     $result['refundOrderId'] = '74062220240409123309810029';
        //     // 退款成功 开始写入退款流水
        //     $finance_data = [];
        //     $finance_data['relation_num'] = $data['refund_order_sn']; // 售后订单编号
        //     $finance_data['relation_user_num'] = $data['user_sn'];
        //     $finance_data['entry'] = 2; // 平台出账
        //     $finance_data['money'] = $data['refund_check_price'];
        //     // $finance_data['money'] = $result['totalAmount']/100;
        //     $finance_data['pay_order_sn'] = $data['pay_order_sn'];
        //     $finance_data['content'] = '用户进行退款，平台支出';
        //     $finance_data['pay_type'] = 1;
        //     $finance_data['act'] = 4; // 申请退款
        //     $financeServices->syncFinance($finance_data);
        //     // 开始写入订单状态
        //     $order_data = [];
        //     $order_data['refund_price'] = $data['refund_check_price'];
        //     $order_data['refund_code'] = $result['refundOrderId'];
        //     $order_data['finish_time'] = date('Y-m-d H:i:s');
        //     // 开始执行 相关操作
        //     $order_data['status'] = 1.3; // 退款完成
        //     if ($data['type'] == 2) {
        //         $order_data['status'] = 2.5; // 退货完成
        //     }
        //     $refund_order_res = $refundOrderModel->where([['refund_order_sn','=',$data['refund_order_sn']]])->save($order_data);
        //     // 写入平台流水记录
        //     $orderServices->syncRefundResult($data['refund_order_sn']);
        //     echo "执行成功"; 
        //  Db::commit();
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     var_dump($e->getMessage());
        // }
        // die();
        // // $param = request()->param();
        // $user_sn = isset($param['user_sn'])?$param['user_sn']:'';
        // $condition = [];
        // $condition[] = ['user_sn','=',$user_sn];
        // $userModel->where($condition)->save(['is_check'=>0,'card_num'=>'']);
        // echo "数据清理成功";
        // $result = $huigongbao->getBankInfo('371081199506108427');
        // var_dump($result); die();
      // $delay_arr = [3,4,5,6];
      // $delay = $delay_arr[array_rand($delay_arr)];
      // echo $delay;
      // $sub_order_sn_arr = ['20230213091930194823','20221128185609197163','20221030160345478882','20221013233541471410'];
      // foreach ($sub_order_sn_arr as $key => $value) {
      //   $msgData = ['time' => date('YmdHis'), 'msgId' => $value, 'jobAction' => 'orderMakeSure'];
      //   $delay = '5';
      //   $taskService->put($msgData, $delay);
      //   echo $value.'--设置成功'."\n";
      // }
      // $str = "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '376739' for key 'PRIMARY'";
      // if(preg_match("/^SQLSTATE\[23000\]:*/",$str)){
      //   var_dump("12121"); die();
      // }
      // $userServices->syncOverAvgBackMoney('20230428174622121108');
      // $sub_order_info = $subOrderModel->where([['sub_order_sn','=','20230428174622121108']])->field('sub_order_sn,user_sn,l_user_sn')->find();
      // if($sub_order_info){
      //   $sub_order_info = $sub_order_info?$sub_order_info->toArray():[];
      //   $msgDatax = ['time' => date('YmdHis'), 'msgId' => $sub_order_info['sub_order_sn'],'user_sn'=>$sub_order_info['user_sn'],'l_user_sn'=>$sub_order_info['l_user_sn'],'act'=>'create', 'jobAction' => 'syncBackMoney'];
      //   $delay = 5;
      //   $taskService->put($msgDatax, $delay);
      // }
        // echo "计划重新执行成功"; die();
    }
    public function doCommit(Task $taskServices, UserServices $userServices)
    {
        $msgData = ['time' => date('YmdHis'), 'msgId' => '', 'jobAction' => 'syncBonusUser'];
        $delay = 10;
        $taskServices->put($msgData, $delay);
        echo "成功执行了对应的操作";
    }
}
